import { ref } from 'vue'

/**
 * @description 读秒功能的button，常用于发送验证码场景
 * @param {Object} obj: {
 *    text: 按钮内文本内容
 *    times: 读秒数
 * }
 */
export const useCountButton = (obj = {}) => {
  const { text = '获取验证码', times = 60 } = obj
  /**显示文字 */
  const btnText = ref(text)
  const disabled = ref(false)
  let timer = null
  let counts = times

  /**开始读秒 */
  function startCount() {
    if (disabled.value) return
    disabled.value = true

    timer = setInterval(() => {
      btnText.value = `${counts--}s后重发`
      if (counts < 0) reset()
    }, 1000)
  }
  /**关闭定时器 ，初始化所有数据*/
  function reset() {
    clearInterval(timer)
    btnText.value = text
    disabled.value = false
    counts = times
  }

  return {
    disabled,
    btnText,
    startCount,
    reset,
  }
}
